package com.sinbad.interview.solution.question02.case01;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 以下是可直接粘贴到  VM options  的配置：Xms100m -Xmx100m -XX:+UseG1GC
 * -
 *
 * @author sinbad.cheng
 * @since 2025-04-14 17:18
 */
public class MaxDuplicateNumberFinder {
    public static void main(String[] args) {
        memoryCheck();

        String filePath = "numbers.txt"; // 你的 txt 文件路径
        Map<Integer, Integer> countMap = new HashMap<>();

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;

            // 一行一行读取数字
            while ((line = reader.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    int number = Integer.parseInt(line.trim());
                    countMap.put(number, countMap.getOrDefault(number, 0) + 1);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 找出出现次数最多的数字
        int maxCount = 0;
        int maxNumber = -1;
        for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
            if (entry.getValue() > maxCount) {
                maxCount = entry.getValue();
                maxNumber = entry.getKey();
            }
        }

        // 出现最多的数字是: 418035，出现次数为: 61
        System.out.println("出现最多的数字是: " + maxNumber + "，出现次数为: " + maxCount);
    }


    public static void memoryCheck() {
        Runtime runtime = Runtime.getRuntime();
        System.out.println("Max Memory: " + runtime.maxMemory() / 1024 / 1024 + "MB");
        System.out.println("Total Memory: " + runtime.totalMemory() / 1024 / 1024 + "MB");
        System.out.println("Free Memory: " + runtime.freeMemory() / 1024 / 1024 + "MB");
    }
}
